import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { CustomerQuotation } from './entities/customer-quotation.entity';
import { CreateCustomerQuotationDto } from './dto/create-customer-quotation.dto';
import { UpdateCustomerQuotationDto } from './dto/update-customer-quotation.dto';
import { CustomerQuotationReplyService } from './customer-quotation-reply.service';
import { UploadPicturesService } from '../common/upload/upload-pictures.service';

@Injectable()
export class CustomerQuotationService {
  constructor(
    @InjectRepository(CustomerQuotation)
    private customerQuotationRepository: Repository<CustomerQuotation>,
    private customerQuotationReplyService: CustomerQuotationReplyService,
    private uploadPicturesService: UploadPicturesService,
  ) {}

  async create(
    createCustomerQuotationDto: CreateCustomerQuotationDto,
  ): Promise<CustomerQuotation> {
    const customerQuotation = this.customerQuotationRepository.create(
      createCustomerQuotationDto,
    );
    return this.customerQuotationRepository.save(customerQuotation);
  }

  async findAll(page: number = 1, limit: number = 50) {
    const skip = (page - 1) * limit;
    const [data, total] = await this.customerQuotationRepository.findAndCount({
      skip,
      take: limit,
      order: { date: 'DESC' },
    });

    return {
      data,
      total,
      page,
      limit,
    };
  }

  async findByQuoteid(quoteid: string): Promise<CustomerQuotation> {
    const customerQuotation = await this.customerQuotationRepository.findOne({
      where: { quoteid },
    });
    if (!customerQuotation) {
      throw new NotFoundException(
        `Customer quotation with quoteid ${quoteid} not found`,
      );
    }

    // 获取报价的图片 - 参考回复的图片逻辑
    if (customerQuotation.picture) {
      console.log('=== findByQuoteid 图片调试 ===');
      console.log('picture 字段:', customerQuotation.picture);
      customerQuotation['uploadpictures'] =
        await this.uploadPicturesService.findByServiceId(
          customerQuotation.picture,
        );
      console.log('查询到的图片:', customerQuotation['uploadpictures']);
    }

    return customerQuotation;
  }

  async findByQuoteidWithReplies(quoteid: string) {
    const customerQuotation = await this.findByQuoteid(quoteid);
    const replies = await this.customerQuotationReplyService.findByQuoteid(
      quoteid,
    );

    // findByQuoteid 已经获取了图片，直接使用
    console.log('=== 客户报价图片调试 ===');
    console.log('客户报价 picture 字段:', customerQuotation.picture);
    console.log(
      '客户报价 uploadpictures:',
      customerQuotation['uploadpictures'],
    );

    return {
      ...customerQuotation,
      replies,
      uploadpictures: customerQuotation['uploadpictures'] || [],
    };
  }

  async update(
    quoteid: string,
    updateCustomerQuotationDto: UpdateCustomerQuotationDto,
  ): Promise<CustomerQuotation> {
    const customerQuotation = await this.findByQuoteid(quoteid);
    Object.assign(customerQuotation, updateCustomerQuotationDto);
    return this.customerQuotationRepository.save(customerQuotation);
  }

  async remove(quoteid: string): Promise<void> {
    const customerQuotation = await this.findByQuoteid(quoteid);
    // customerQuotation.deleted = true;
    // await this.customerQuotationRepository.save(customerQuotation);
    await this.customerQuotationRepository.remove(customerQuotation);
  }





  async search(keyword: string, page: number = 1, limit: number = 50) {
    if (!keyword || keyword.trim() === '') {
      throw new BadRequestException('搜索关键词不能为空');
    }

    const skip = (page - 1) * limit;
    const [data, total] = await this.customerQuotationRepository.findAndCount({
      where: [
        { title: Like(`%${keyword}%`) },
        { customername: Like(`%${keyword}%`) },
        { content: Like(`%${keyword}%`) },
      ],
      skip,
      take: limit,
      order: { date: 'DESC' },
    });

    return {
      data,
      total,
      page,
      limit,
    };
  }
} 